<!--
 * @Author: user
 * @Date: 2025-09-22 11:00:00
 * @LastEditor: user
 * @LastEditTime: 2025-09-22 11:38:21
 * @Description: 我发布的任务管理组件
 -->
 <template>
  <div class="my-tasks-container" :style="{ height: view.height-142 + 'px' }">
    <!-- 头部区域 -->
    <div class="header-section">
      <div class="page-title">
        <el-icon class="title-icon" size="24">
          <User />
        </el-icon>
        <span>我发布的任务</span>
      </div>
      
      <div class="header-actions">
        <el-button 
          type="primary" 
          :icon="Plus" 
          @click="handleCreateTask"
        >
          发布新任务
        </el-button>
        
        <el-select 
          v-model="statusFilter" 
          placeholder="筛选状态" 
          style="width: 140px;"
          clearable
        >
          <el-option label="全部状态" value="" />
          <el-option label="未承接" value="未承接" />
          <el-option label="已承接" value="已承接" />
          <el-option label="进行中" value="进行中" />
          <el-option label="已完成" value="已完成" />
          <el-option label="已关闭" value="已关闭" />
        </el-select>
        
        <el-input
          v-model="searchText"
          placeholder="搜索任务名称、岗位需求..."
          style="width: 300px;"
          clearable
        >
          <template #prefix>
            <el-icon><Search /></el-icon>
          </template>
        </el-input>
      </div>
    </div>

    <!-- 统计卡片 -->
    <div class="stats-section">
      <el-row :gutter="16">
        <el-col :xs="12" :sm="6" :md="6" :lg="6">
          <el-card shadow="hover" class="stats-card">
            <div class="stats-item">
              <div class="stats-value">{{ totalPublishedCount }}</div>
              <div class="stats-label">发布总数</div>
              <el-icon class="stats-icon" size="32" color="#409eff">
                <Document />
              </el-icon>
            </div>
          </el-card>
        </el-col>
        
        <el-col :xs="12" :sm="6" :md="6" :lg="6">
          <el-card shadow="hover" class="stats-card">
            <div class="stats-item">
              <div class="stats-value">{{ pendingCount }}</div>
              <div class="stats-label">待承接</div>
              <el-icon class="stats-icon" size="32" color="#e6a23c">
                <Clock />
              </el-icon>
            </div>
          </el-card>
        </el-col>
        
        <el-col :xs="12" :sm="6" :md="6" :lg="6">
          <el-card shadow="hover" class="stats-card">
            <div class="stats-item">
              <div class="stats-value">{{ inProgressCount }}</div>
              <div class="stats-label">已承接</div>
              <el-icon class="stats-icon" size="32" color="#67c23a">
                <Loading />
              </el-icon>
            </div>
          </el-card>
        </el-col>
        
        <el-col :xs="12" :sm="6" :md="6" :lg="6">
          <el-card shadow="hover" class="stats-card">
            <div class="stats-item">
              <div class="stats-value">{{ completedCount }}</div>
              <div class="stats-label">承接中</div>
              <el-icon class="stats-icon" size="32" color="#909399">
                <CircleCheck />
              </el-icon>
            </div>
          </el-card>
        </el-col>
      </el-row>
    </div>

    <!-- 数据表格 -->
    <div class="table-section">
      <el-card shadow="never">
        <el-table 
          :data="filteredTasks" 
          style="width: 100%"
          row-key="id"
          v-loading="loading"
          element-loading-text="加载中..."
          empty-text="您还没有发布任何任务"
          :height="tableHeight"
        >
          <el-table-column prop="taskName" label="任务名称" width="220">
            <template #default="{ row }">
              <div class="task-name-cell">
                <div class="task-title" @click="handleViewDetail(row)" style="cursor: pointer; color: #409eff;">
                  {{ row.taskName }}
                </div>
                <div class="task-level">{{ row.taskLevel }}</div>
                <div class="publish-time">发布于：{{ row.createdAt }}</div>
              </div>
            </template>
          </el-table-column>

          <el-table-column prop="positionRequirement" label="岗位需求" width="120">
            <template #default="{ row }">
              <el-tag 
                :type="getPositionType(row.positionRequirement)" 
                size="small"
                class="position-tag"
              >
                {{ row.positionRequirement }}
              </el-tag>
            </template>
          </el-table-column>

          <el-table-column prop="personnelCount" label="需求人数" width="100" align="center">
            <template #default="{ row }">
              <el-tag type="info" size="small">
                {{ row.personnelCount }}人
              </el-tag>
            </template>
          </el-table-column>

          <el-table-column prop="taskStatus" label="任务状态" width="120">
            <template #default="{ row }">
              <el-tag 
                :type="getStatusType(row.taskStatus)" 
                size="small"
                class="status-tag"
              >
                {{ row.taskStatus }}
              </el-tag>
            </template>
          </el-table-column>

          <el-table-column label="报名情况" width="180">
            <template #default="{ row }">
              <div class="applicant-status">
                <div class="applicant-count">
                  <el-icon><UserFilled /></el-icon>
                  <span>{{ row.applicants.length }}人报名</span>
                </div>
                <el-button 
                  type="primary" 
                  size="small" 
                  text
                  @click="handleViewApplicants(row)"
                  :disabled="row.applicants.length === 0"
                >
                  查看报名者
                </el-button>
              </div>
            </template>
          </el-table-column>

          <el-table-column label="承接情况" width="200">
            <template #default="{ row }">
              <div class="assignee-status">
                <div v-if="row.assignees && row.assignees.length > 0" class="assigned">
                  <div class="assignee-list">
                    <el-tag 
                      v-for="assignee in row.assignees.slice(0, 2)" 
                      :key="assignee"
                      size="small"
                      type="success"
                      class="assignee-tag"
                    >
                      {{ assignee }}
                    </el-tag>
                    <span v-if="row.assignees.length > 2" class="more-assignees">
                      +{{ row.assignees.length - 2 }}
                    </span>
                  </div>
                  <el-button 
                    type="success" 
                    size="small" 
                    text
                    @click="handleManageAssignees(row)"
                  >
                    管理承接人
                  </el-button>
                </div>
                <div v-else class="unassigned">
                  <span class="no-assignee">暂无承接人</span>
                  <el-button 
                    type="warning" 
                    size="small" 
                    text
                    @click="handleAssignTask(row)"
                    :disabled="row.applicants.length === 0"
                  >
                    分配任务
                  </el-button>
                </div>
              </div>
            </template>
          </el-table-column>

          <el-table-column prop="deadline" label="截止日期" width="120">
            <template #default="{ row }">
              <div class="deadline-cell">
                <el-icon><Calendar /></el-icon>
                <span :class="{ 'deadline-urgent': isDeadlineUrgent(row.deadline) }">
                  {{ row.deadline }}
                </span>
              </div>
            </template>
          </el-table-column>

          <el-table-column prop="taskContent" label="任务描述" min-width="200">
            <template #default="{ row }">
              <div class="task-content">
                <!-- <el-tooltip :content="row.taskContent" placement="top-start"> -->
                  <div class="content-text" :title="row.taskContent">
                    {{ truncateText(row.taskContent, 80) }}
                  </div>
                <!-- </el-tooltip> -->
              </div>
            </template>
          </el-table-column>

          <el-table-column label="任务进度" width="150">
            <template #default="{ row }">
              <div class="progress-cell">
                <el-progress 
                  :percentage="getTaskProgress(row)" 
                  :color="getProgressColor(row)"
                  :stroke-width="8"
                />
                <div class="progress-text">{{ getProgressText(row) }}</div>
              </div>
            </template>
          </el-table-column>

          <el-table-column label="操作" width="200" fixed="right">
            <template #default="{ row }">
              <div class="action-buttons">
                <el-button 
                  type="primary" 
                  size="small" 
                  text
                  @click="handleViewDetail(row)"
                >
                  详情
                </el-button>
                <el-button 
                  type="success" 
                  size="small" 
                  text
                  @click="handleEditTask(row)"
                  :disabled="['已完成', '已关闭'].includes(row.taskStatus)"
                >
                  编辑
                </el-button>
                <el-dropdown @command="(command) => handleDropdownCommand(command, row)">
                  <el-button type="info" size="small" text>
                    更多<el-icon class="el-icon--right"><ArrowDown /></el-icon>
                  </el-button>
                  <template #dropdown>
                    <el-dropdown-menu>
                      <el-dropdown-item command="close" :disabled="['已完成', '已关闭'].includes(row.taskStatus)">
                        关闭任务
                      </el-dropdown-item>
                      <el-dropdown-item command="complete" :disabled="row.taskStatus !== '进行中'">
                        标记完成
                      </el-dropdown-item>
                      <el-dropdown-item command="copy">
                        复制任务
                      </el-dropdown-item>
                      <el-dropdown-item command="delete" divided>
                        删除任务
                      </el-dropdown-item>
                    </el-dropdown-menu>
                  </template>
                </el-dropdown>
              </div>
            </template>
          </el-table-column>
        </el-table>
      </el-card>
    </div>

    <!-- 任务详情对话框 -->
    <TaskDetail
      v-model:visible="detailVisible"
      :task="selectedTask"
      @refresh="loadMyTasks"
    />

    <!-- 报名人管理对话框 -->
    <ApplicantsDialog
      v-model:visible="applicantsVisible"
      :task="selectedTask"
      @refresh="loadMyTasks"
    />

    <!-- 承接人管理对话框 -->
    <AssigneeManageDialog
      v-model:visible="assigneeManageVisible"
      :task="selectedTask"
      @refresh="loadMyTasks"
    />

    <!-- 任务分配对话框 -->
    <TaskAssignDialog
      v-model:visible="taskAssignVisible"
      :task="selectedTask"
      @refresh="loadMyTasks"
    />

    <!-- 任务表单对话框 -->
    <TaskForm
      v-model:visible="taskFormVisible"
      :task="selectedTask"
      :is-edit="isEditMode"
      @refresh="loadMyTasks"
    />
  </div>
</template>

<script setup lang="ts">
import { defineComponent, reactive, ref, toRefs, onMounted, watch, computed } from "vue";
import { ElMessage, ElMessageBox } from "element-plus";
import {
  User,
  Search,
  CircleCheck,
  Clock,
  Loading,
  Calendar,
  Plus,
  UserFilled,
  ArrowDown
} from '@element-plus/icons-vue';
import TaskDetail from './TaskDetail.vue';
import ApplicantsDialog from './ApplicantsDialog.vue';
import AssigneeManageDialog from './ApplicantsDialog.vue';
import TaskAssignDialog from './ApplicantsDialog.vue';
import TaskForm from './TaskForm.vue';

// 任务信息接口定义
interface TaskInfo {
  id: number;
  initiator: string;
  taskLevel: string;
  taskName: string;
  positionRequirement: string;
  taskContent: string;
  personnelCount: number;
  applicants: string[];
  assignees: string[];
  workHours: {
    startDate: string;
    endDate: string;
  };
  deadline: string;
  taskStatus: string;
  attachments: string[] | null;
  createdAt?: string;
  updatedAt?: string;
  progress?: number; // 任务进度百分比
}

onMounted(() => {
  loadMyTasks();
});

const view = reactive({
  height: window.innerHeight,
});

// 响应式数据
const searchText = ref<string>('');
const statusFilter = ref<string>('');
const loading = ref<boolean>(false);
const myTaskList = ref<TaskInfo[]>([]);

// 对话框控制
const detailVisible = ref(false);
const applicantsVisible = ref(false);
const assigneeManageVisible = ref(false);
const taskAssignVisible = ref(false);
const taskFormVisible = ref(false);
const isEditMode = ref(false);
const selectedTask = ref<TaskInfo | null>(null);

// 计算属性
const filteredTasks = computed(() => {
  let tasks = myTaskList.value;
  
  // 状态筛选
  if (statusFilter.value) {
    tasks = tasks.filter(task => task.taskStatus === statusFilter.value);
  }
  
  // 搜索筛选
  if (searchText.value) {
    tasks = tasks.filter(task => 
      task.taskName.toLowerCase().includes(searchText.value.toLowerCase()) ||
      task.positionRequirement.toLowerCase().includes(searchText.value.toLowerCase())
    );
  }
  
  return tasks;
});

const totalPublishedCount = computed(() => myTaskList.value.length);

const pendingCount = computed(() => 
  myTaskList.value.filter(t => t.taskStatus === '未承接').length
);

const inProgressCount = computed(() => 
  myTaskList.value.filter(t => ['已承接', '进行中'].includes(t.taskStatus)).length
);

const completedCount = computed(() => 
  myTaskList.value.filter(t => ['已完成', '已关闭'].includes(t.taskStatus)).length
);

const tableHeight = computed(() => {
  return view.height - 360;
});

// 方法
const loadMyTasks = () => {
  loading.value = true;
  
  // 模拟当前用户发布的任务数据
  setTimeout(() => {
    myTaskList.value = [
      {
        id: 1,
        initiator: "当前用户", // 这里应该是当前登录用户
        taskLevel: "部门任务",
        taskName: "水库安全监测数据分析",
        positionRequirement: "科研助理",
        taskContent: "负责分析山东省小型水库监测数据，包括水位、流量等关键指标的统计分析，并编制相关技术报告。需要熟悉数据分析软件的使用。",
        personnelCount: 2,
        applicants: ["李明", "王小红", "赵强"],
        assignees: ["李明", "王小红"],
        workHours: {
          startDate: "2025-09-20",
          endDate: "2025-10-15"
        },
        deadline: "2025-10-15",
        taskStatus: "进行中",
        attachments: ["监测数据.xlsx", "技术要求.pdf"],
        createdAt: "2025-09-18",
        updatedAt: "2025-09-19",
        progress: 65
      },
      {
        id: 2,
        initiator: "当前用户",
        taskLevel: "项目任务",
        taskName: "防洪调度系统UI优化",
        positionRequirement: "技术开发",
        taskContent: "优化防洪调度系统的用户界面，提升用户体验，包括响应式布局改进、交互优化等工作。",
        personnelCount: 1,
        applicants: ["张技术", "刘开发"],
        assignees: [],
        workHours: {
          startDate: "2025-10-01",
          endDate: "2025-11-30"
        },
        deadline: "2025-11-30",
        taskStatus: "未承接",
        attachments: ["UI设计稿.figma", "需求文档.docx"],
        createdAt: "2025-09-17",
        updatedAt: "2025-09-18",
        progress: 0
      },
      {
        id: 3,
        initiator: "当前用户",
        taskLevel: "部门任务",
        taskName: "年度预算报告编制",
        positionRequirement: "业务秘书",
        taskContent: "编制2026年度部门预算报告，包括各项支出预算、设备采购计划等内容的整理和汇总。",
        personnelCount: 1,
        applicants: ["王秘书"],
        assignees: ["王秘书"],
        workHours: {
          startDate: "2025-09-15",
          endDate: "2025-09-30"
        },
        deadline: "2025-09-30",
        taskStatus: "已完成",
        attachments: ["预算模板.xlsx"],
        createdAt: "2025-09-10",
        updatedAt: "2025-09-30",
        progress: 100
      },
    ];

    loading.value = false;
  }, 800);
};

// 任务操作方法
const handleCreateTask = () => {
  selectedTask.value = null;
  isEditMode.value = false;
  taskFormVisible.value = true;
};

const handleEditTask = (task: TaskInfo) => {
  selectedTask.value = { ...task };
  isEditMode.value = true;
  taskFormVisible.value = true;
};

const handleViewDetail = (task: TaskInfo) => {
  selectedTask.value = task;
  detailVisible.value = true;
};

const handleViewApplicants = (task: TaskInfo) => {
  selectedTask.value = task;
  applicantsVisible.value = true;
};

const handleManageAssignees = (task: TaskInfo) => {
  selectedTask.value = task;
  assigneeManageVisible.value = true;
};

const handleAssignTask = (task: TaskInfo) => {
  selectedTask.value = task;
  taskAssignVisible.value = true;
};

const handleDropdownCommand = async (command: string, task: TaskInfo) => {
  switch (command) {
    case 'close':
      await handleCloseTask(task);
      break;
    case 'complete':
      await handleCompleteTask(task);
      break;
    case 'copy':
      handleCopyTask(task);
      break;
    case 'delete':
      await handleDeleteTask(task);
      break;
  }
};

const handleCloseTask = async (task: TaskInfo) => {
  try {
    await ElMessageBox.confirm(
      `确定要关闭任务"${task.taskName}"吗？关闭后将无法继续进行。`,
      '确认关闭任务',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      }
    );
    
    const index = myTaskList.value.findIndex(t => t.id === task.id);
    if (index > -1) {
      myTaskList.value[index].taskStatus = '已关闭';
      myTaskList.value[index].updatedAt = new Date().toISOString().split('T')[0];
      ElMessage.success('任务已关闭');
    }
  } catch {
    ElMessage.info('已取消操作');
  }
};

const handleCompleteTask = async (task: TaskInfo) => {
  try {
    await ElMessageBox.confirm(
      `确定要将任务"${task.taskName}"标记为已完成吗？`,
      '确认完成任务',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'success',
      }
    );
    
    const index = myTaskList.value.findIndex(t => t.id === task.id);
    if (index > -1) {
      myTaskList.value[index].taskStatus = '已完成';
      myTaskList.value[index].progress = 100;
      myTaskList.value[index].updatedAt = new Date().toISOString().split('T')[0];
      ElMessage.success('任务已标记为完成');
    }
  } catch {
    ElMessage.info('已取消操作');
  }
};

const handleCopyTask = (task: TaskInfo) => {
  const newTask = {
    ...task,
    id: Date.now(),
    taskName: `${task.taskName} (副本)`,
    applicants: [],
    assignees: [],
    taskStatus: '未承接',
    progress: 0,
    createdAt: new Date().toISOString().split('T')[0],
    updatedAt: new Date().toISOString().split('T')[0]
  };
  
  myTaskList.value.unshift(newTask);
  ElMessage.success('任务已复制');
};

const handleDeleteTask = async (task: TaskInfo) => {
  try {
    await ElMessageBox.confirm(
      `确定要删除任务"${task.taskName}"吗？此操作不可恢复。`,
      '确认删除',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      }
    );
    
    const index = myTaskList.value.findIndex(t => t.id === task.id);
    if (index > -1) {
      myTaskList.value.splice(index, 1);
      ElMessage.success('删除成功');
    }
  } catch {
    ElMessage.info('已取消删除');
  }
};

// 工具方法
const getPositionType = (position: string) => {
  const positionMap: Record<string, string> = {
    '科研助理': 'success',
    '业务秘书': 'primary',
    '技术开发': 'warning'
  };
  return positionMap[position] || 'info';
};

const getStatusType = (status: string) => {
  const statusMap: Record<string, string> = {
    '未承接': 'warning',
    '已承接': 'primary',
    '进行中': 'success',
    '已完成': 'info',
    '已关闭': 'danger'
  };
  return statusMap[status] || 'info';
};

const getTaskProgress = (task: TaskInfo) => {
  return task.progress || 0;
};

const getProgressColor = (task: TaskInfo) => {
  const progress = task.progress || 0;
  if (progress < 30) return '#e6a23c';
  if (progress < 70) return '#409eff';
  return '#67c23a';
};

const getProgressText = (task: TaskInfo) => {
  const progress = task.progress || 0;
  if (task.taskStatus === '已完成') return '已完成';
  if (task.taskStatus === '已关闭') return '已关闭';
  if (task.taskStatus === '未承接') return '待承接';
  return `${progress}%`;
};

const isDeadlineUrgent = (deadline: string) => {
  const today = new Date();
  const deadlineDate = new Date(deadline);
  const diffTime = deadlineDate.getTime() - today.getTime();
  const diffDays = Math.ceil(diffTime / (1000 * 60 * 60 * 24));
  return diffDays <= 7 && diffDays >= 0;
};

const truncateText = (text: string, maxLength: number) => {
  if (text.length <= maxLength) return text;
  return text.substring(0, maxLength) + '...';
};
</script>

<style lang="scss" scoped>
.my-tasks-container {
  padding: 0 20px;
  background-color: #f5f7fa;
  overflow: auto;
}

.header-section {
  background: white;
  border-radius: 8px;
  padding: 20px;
  margin-bottom: 16px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
  display: flex;
  justify-content: space-between;
  align-items: center;
  flex-wrap: wrap;
  gap: 16px;

  .page-title {
    display: flex;
    align-items: center;
    font-size: 20px;
    font-weight: 600;
    color: #303133;
    
    .title-icon {
      margin-right: 8px;
      color: #409eff;
    }
  }

  .header-actions {
    display: flex;
    align-items: center;
    gap: 12px;
    flex-wrap: wrap;
  }
}

.stats-section {
  margin-bottom: 16px;

  .stats-card {
    .stats-item {
      display: flex;
      align-items: center;
      justify-content: space-between;
      
      .stats-value {
        font-size: 28px;
        font-weight: bold;
        color: #409eff;
      }
      
      .stats-label {
        color: #909399;
        margin-top: 4px;
        font-size: 14px;
      }
      
      .stats-icon {
        opacity: 0.8;
      }
    }
  }
}

.table-section {
  background: white;
  border-radius: 8px;
  overflow: hidden;
}

.task-name-cell {
  .task-title {
    font-weight: 500;
    margin-bottom: 4px;
    
    &:hover {
      text-decoration: underline;
    }
  }
  
  .task-level {
    font-size: 12px;
    color: #909399;
    margin-bottom: 2px;
  }
  
  .publish-time {
    font-size: 11px;
    color: #c0c4cc;
  }
}

.applicant-status {
  .applicant-count {
    display: flex;
    align-items: center;
    margin-bottom: 4px;
    font-size: 13px;
    color: #606266;
    
    .el-icon {
      margin-right: 4px;
      color: #409eff;
    }
  }
}

.assignee-status {
  .assigned {
    .assignee-list {
      display: flex;
      align-items: center;
      margin-bottom: 4px;
      flex-wrap: wrap;
      gap: 4px;
      
      .assignee-tag {
        margin: 0;
      }
      
      .more-assignees {
        color: #909399;
        font-size: 12px;
      }
    }
  }
  
  .unassigned {
    .no-assignee {
      color: #909399;
      font-size: 12px;
      display: block;
      margin-bottom: 4px;
    }
  }
}

.deadline-cell {
  display: flex;
  align-items: center;
  font-size: 13px;
  
  :deep(.el-icon) {
    margin-right: 6px;
    color: #909399;
  }
  
  .deadline-urgent {
    color: #f56c6c;
    font-weight: 500;
  }
}

.task-content {
  .content-text {
    line-height: 1.4;
    color: #ccc;
    cursor: pointer;
    
    &:hover {
      color: #409eff;
    }
  }
}

.progress-cell {
  .progress-text {
    text-align: center;
    font-size: 12px;
    color: #606266;
    margin-top: 4px;
  }
}

.position-tag, .status-tag {
  font-weight: 500;
}

.action-buttons {
  display: flex;
  gap: 8px;
  align-items: center;
}

// 响应式样式
@media (max-width: 768px) {
  .my-tasks-container {
    padding: 10px;
  }
  
  .header-section {
    flex-direction: column;
    align-items: stretch;
    
    .header-actions {
      justify-content: center;
      flex-wrap: wrap;
    }
  }
  
  .stats-section {
    .el-col {
      margin-bottom: 12px;
    }
  }
}

@media (max-width: 480px) {
  .header-actions {
    flex-direction: column;
    align-items: stretch;
    
    .el-input, .el-select {
      width: 100% !important;
    }
  }
}
</style>

